package com.jiujiu.utitls;

import com.google.common.base.CaseFormat;
import com.jiujiu.model.DataBaseCommon.EntityModelBySql;
import com.jiujiu.model.DataBaseCommon.ModelEntitys;
import com.jiujiu.model.DataBaseCommon.SqlEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.sql.*;

/**
 * @author ZhaoJunZhou
 * @Date 2020/10/13
 */
public class SqlDriver {
    private static final Logger log = Logger.getLogger(SqlDriver.class);
    private static String _url;
    private static String _driverClassName;
    private static String _username;
    private static String _password;
    private static Integer sate=0;
    private static Connection connection;
    public static void iniDriverManager(String url, String driverClassName, String username, String password) {
        _url = url;
        _driverClassName = driverClassName;
        _password = password;
        _username = username;
        try{
            //加载MySql的驱动类
            Class.forName(driverClassName);
            log.info("找驱动程序类 ，加载驱动成功！driverClassName:" + _driverClassName);
        }catch(ClassNotFoundException e){
            log.error("找不到驱动程序类 ，加载驱动失败！driverClassName:" + driverClassName);
            e.printStackTrace() ;
        }
        try {
            connection= DriverManager.getConnection(
                    _url, _username, _password);
            sate = 1;
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    public static Object executeSql(SqlEntity sqlEntity) {
        String sql = sqlEntity.getSql();
        String[] s3 = new String[0];
        return executeSql(sql, s3,sqlEntity);
    }

    /**
     *
     * @param sql
     * @param args 可以添加参数用来替代问号
     * @return
     */
    public static Object executeSql(String sql, String[] args,SqlEntity sqlEntity) {
        if (sate == 1) {
            try {
                log.info("执行的sql: "+sql);
                log.info("参数:"+ StringUtils.join(args, ","));
                PreparedStatement statement = connection.prepareStatement(sql,args);
                statement.execute();
                ResultSetMetaData resultSetMetaData = statement.getMetaData();
                EntityModelBySql[] entityModelBySqls=new EntityModelBySql[resultSetMetaData.getColumnCount()];
                for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {

                    entityModelBySqls[i - 1] = new EntityModelBySql(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,resultSetMetaData.getColumnLabel(i)),resultSetMetaData.getColumnTypeName(i),resultSetMetaData.getColumnLabel(i));
                }
               new ModelEntitys(sqlEntity, entityModelBySqls).analysis();
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
            log.info("没有对数据库驱动经行初始化。。。。。");
        }
        return null;
    }
}
